package com.fyb.basic.lock.DeadLock;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class DeadLockDemo {
    public static void main(String[] args) {
        Object resourceA = new Object();
        Object resourceB = new Object();
        // 检测死锁代码
        final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
            // 查找死锁的线程
                long[] deadlockedThreads = threadMXBean.findDeadlockedThreads();
                if(deadlockedThreads != null && deadlockedThreads.length > 0){
                    // 获得死锁线程的信息
                    ThreadInfo[] threadInfo = threadMXBean.getThreadInfo(deadlockedThreads);
                    for (ThreadInfo th : threadInfo){
                        System.out.println(th.getThreadId() +"===" + th.getThreadName() );
                    }
                }
            }
        };

        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
        // 稍等一秒 然后每隔两秒进行扫描
        executorService.scheduleAtFixedRate(runnable,1,2, TimeUnit.SECONDS);

        new Thread(new MyTask(resourceA, resourceB), "Thread-A").start();
        new Thread(new MyTask(resourceB, resourceA), "Thread-B").start();
    }
}
